/*
 * =============================================================================
 * Copyright by Benjamin Sempere,
 * All rights reserved.
 * =============================================================================
 * Author  : Benjamin Sempere
 * E-mail  : benjamin@sempere.org
 * Homepage: www.sempere.org
 * =============================================================================
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.sempere.commons.jpa;

import java.util.Collection;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

/**
 * Base class for any Data Access Object (DAO) built on JPA API.
 * 
 * @author bsempere
 */
public abstract class AbstractDAO {

	private EntityManager entityManager;

	/**
	 * Default class constructor
	 */
	public AbstractDAO() {
	}

	/**
	 * Constructor that takes the entityManager to be used
	 * 
	 * @param entityManager the entityManager to inject
	 */
	public AbstractDAO(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	/**
	 * Returns the entity manager built around the given persistence unit name
	 * 
	 * @return EntityManager
	 */
	public EntityManager getEntityManager() {
		return this.entityManager;
	}

	// *************************************************************************
	//
	// Commons methods ...
	//
	// *************************************************************************

	protected <T> T find(Class<T> entityClass, Object entityPK) {
		T entity = this.getEntityManager().find(entityClass, entityPK);
		if (entity == null) {
			throw new NoResultException("Entity with class [" + entityClass + "] and  PK [" + entityPK + "] does not exist in the database.");
		}
		return entity;
	}

	protected <T> T persist(T entity) {
		this.getEntityManager().persist(entity);
		return entity;
	}

	protected <T> T merge(T entity) {
		this.getEntityManager().merge(entity);
		return entity;
	}

	protected <T> void remove(Class<T> entityClass, Object entityPK) {
		T entity = this.find(entityClass, entityPK);
		this.getEntityManager().remove(entity);
	}

	protected <T> T getResultFromNamedQuery(Class<T> entityClass, String queryName) {
		return this.getResultFromNamedQuery(entityClass, queryName, null);
	}

	@SuppressWarnings("unchecked")
	protected <T> T getResultFromNamedQuery(Class<T> entityClass, String queryName, Map<String, Object> parameters) {
		Query query = this.getEntityManager().createNamedQuery(queryName);
		if (parameters != null) {
			for (String parameterName : parameters.keySet()) {
				query.setParameter(parameterName, parameters.get(parameterName));
			}
		}
		return (T) query.getSingleResult();
	}

	protected <T> Collection<T> getResultsFromNamedQuery(Class<T> entityClass, String queryName) {
		return this.getResultsFromNamedQuery(entityClass, queryName, null);
	}

	@SuppressWarnings("unchecked")
	protected <T> Collection<T> getResultsFromNamedQuery(Class<T> entityClass, String queryName, Map<String, Object> parameters) {
		Query query = this.getEntityManager().createNamedQuery(queryName);
		if (parameters != null) {
			for (String parameterName : parameters.keySet()) {
				query.setParameter(parameterName, parameters.get(parameterName));
			}
		}
		return (Collection<T>) query.getResultList();
	}

	// ********************************************************************************
	//
	// Setter for dependencies injection
	//
	// ********************************************************************************

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
}
